package com.dh.blog.controllers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ewei.web.common.exception.MessageRuntimeException;
import com.ewei.web.common.json.JsonUtils;
import com.ewei.web.common.utils.FileToolsBar;
import com.mysql.jdbc.StringUtils;
/**
 * 文件控制器
 * @author David
 *
 */
@RequestMapping("/f")
@Controller
public class FileController {
	private static final Pattern pattern = Pattern.compile("/f(/[\\S]+)");
	/**
	 * 因为我的路径可能带有斜杠,要特殊处理
	 */
	@Resource
	private Properties config;
	@RequestMapping(value = "/**",method=RequestMethod.GET)
	public void read(HttpServletRequest request,HttpServletResponse response){
		String abs = "";
		String uri = request.getRequestURI();
		Matcher matcher = pattern.matcher(uri);
		if(matcher.find()){
			abs = matcher.group(1);
		}
		//只允许从主动暴露的接口读文件
		List<String> exposes = 
				JsonUtils.fromJson(config.getProperty("expose_dir"), String.class);
		int flag = 0;
		for(String expose :exposes){
			if(abs.startsWith(expose)){
				flag = 1;
			}
		}
		if(flag == 1){
			String diskDir = config.getProperty("file_disk_dir");
			abs = (StringUtils.isNullOrEmpty(diskDir)?"":diskDir) + abs;
			try{
				FileToolsBar.readFileIntoStream(new File(abs),
						response.getOutputStream());
			}catch(IOException ex){
				throw new MessageRuntimeException(ex);
			}
		}else{
			response.setStatus(404);//404
		}
	}
}
